<script lang="ts" setup>
import type { FormRules } from 'element-plus';

import type { Dict } from '@croco/framework/types';

import { onBeforeMount, reactive, ref } from 'vue';

import { VIcon } from '@croco/framework/icons';
import { $t } from '@croco/framework/locales';
import { useUserStore } from '@croco/framework/stores';

import { getDictTrim } from '#/api';
import { service } from '#/api/request';

const userStore = useUserStore();

const formRef = ref();
const enums = reactive<{
    sex: Array<Dict> | undefined;
}>({
    sex: undefined,
});
const form = ref<{ [key: string]: any }>({
    id: undefined,
    username: undefined,
    nickname: undefined,
    sex: '2',
    avatar: undefined,
    birthDate: undefined,
    email: undefined,
    mobile: undefined,
    address: undefined,
    description: undefined,
});

const rules = ref<FormRules>({
    email: [
        { required: true, message: '邮箱不能为空', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址（如：user@example.com）', trigger: 'blur' },
        { pattern: /^[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i, message: '邮箱格式不正确', trigger: 'blur' },
    ],
    mobile: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { pattern: /^1(3\d|4[014-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: '请输入正确的11位手机号码', trigger: 'blur' },
    ],
});

const onSubmit = () => {
    formRef.value.validate((valid: boolean) => {
        if (valid) {
            service.put('/profile/edit', form.value).then(({ code }) => {
                code === 200 && userStore.updateUserInfo(form.value);
            });
        }
    });
};

onBeforeMount(() => {
    getDictTrim(['sys_user_sex'])
        .then((rs) => {
            enums.sex = rs[0] ?? [];
        })
        .then(() => {
            Object.keys(form.value).forEach((key) => {
                form.value[key] = key === 'deptName' ? userStore.userInfo.dept.name : userStore.userInfo[key];
            });
        });
});
</script>

<template>
    <el-tabs model-value="first" class="kt-tabs__button account-tabs">
        <el-tab-pane name="first">
            <template #label>
                <span style="font-size: 20px">个人信息</span>
            </template>
            <el-form ref="formRef" :model="form" size="large" :rules="rules" :validate-on-rule-change="false" label-width="100px" style="max-width: 500px">
                <el-form-item prop="id" v-show="false">
                    <el-input v-model="form.id" />
                </el-form-item>
                <el-form-item prop="avatar" v-show="false">
                    <el-input v-model="form.avatar" />
                </el-form-item>
                <el-form-item label="账号" prop="username">
                    <el-input v-model="form.username" disabled />
                    <div class="el-form-item-msg">账号信息用于登录，系统不允许修改</div>
                </el-form-item>
                <el-form-item label="真实姓名" prop="nickname">
                    <el-input v-model="form.nickname" clearable />
                </el-form-item>
                <el-form-item label="所属部门">
                    <el-input :model-value="userStore.userInfo.dept.name" disabled />
                </el-form-item>
                <el-form-item label="联系号码" prop="mobile" required>
                    <el-input v-model="form.mobile" />
                </el-form-item>
                <el-form-item label="电子邮箱" prop="email" required>
                    <el-input v-model="form.email" />
                </el-form-item>
                <el-form-item label="出生日期" prop="birthDate">
                    <!--Computed is still dirty after getter evaluation, likely because a computed is mutating its own dependency in its getter-->
                    <el-date-picker v-model="form.birthDate" type="date" value-format="YYYY-MM-DD" style="width: 100%" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="form.sex">
                        <el-radio v-for="item in enums.sex" :key="item.value" :value="item.value" :label="item.label" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="家庭住址" prop="address">
                    <el-input v-model="form.address" />
                </el-form-item>
                <el-form-item label="个性签名" prop="description">
                    <el-input v-model="form.description" resize="none" type="textarea" :rows="6" maxlength="200" show-word-limit />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit()">
                        <template #icon>
                            <VIcon icon="carbon:save" />
                        </template>
                        {{ $t('common.confirm') }}
                    </el-button>
                </el-form-item>
            </el-form>
        </el-tab-pane>
    </el-tabs>
</template>

<style scoped></style>
